package edu.wfu.preparedDishes.user.interceptor;


import com.google.common.collect.Lists;
import edu.wfu.preparedDishes.user.entity.UserEntity;
import edu.wfu.preparedDishes.user.service.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Objects;

/**
 * @Description: jwt拦截器
 */
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(request.getRequestURI());
        // 从 http 请求头中取出 token
        String token = request.getHeader("token");
        System.out.println("请求里的token=" + token);
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        if (StringUtils.isBlank(token)) {
            throw new RuntimeException("无token，请重新登录");
        }
        // 获取 token中的userId,根据userId查询数据库，检查用户是否存在
        String openid;
        String userId;
        try {
            openid = Jwts.parser().setSigningKey("7122").parseClaimsJws(token).getBody().getSubject();
            userId = userService.getUser(openid).getUserId();
            log.debug("openid = {}", openid);
            log.debug("userId = {}", userId);
            if (StringUtils.isBlank(openid)) {
                throw new RuntimeException("token已过期，请重新登录");
            }
            if (Objects.isNull(userId)) {
                throw new RuntimeException("token已过期，请重新登录");
            }
            request.setAttribute("userId", userId);
        } catch (Exception e) {
            throw new RuntimeException("token已过期，请重新登录");
        }
        return true;
    }
}
